﻿using LocoyApp.Locoy.Entry;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace LocoyApp.Locoy
{
    public class TitleRewrite : LocoyCode
    {
        /// <summary>
        /// 执行方法，不能修改类和方法名称。
        /// </summary>
        /// <param name="content">标签内容</param>
        /// <param name="response">页面响应，包含了Url、原始Html等属性</param>
        /// <returns>返回处理后的标签内容</returns>
        public string Run(string content, ResponseEntry response)
        {
            var items = BaiduDropdown(content);
            var randTitle = Rand(items);
            content = StringFormat(content, randTitle);
            //在这里编写处理代码
            return content;
        }

        private List<string> BaiduDropdown(string keyword)
        {
            var url = string.Format("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd={0}&json=1&ie=utf-8", HttpUtility.HtmlEncode(keyword));
            var text = Request(url);
            text = text.Replace(");", "").Replace("window.baidu.sug(", "");
            var regex = new System.Text.RegularExpressions.Regex("\"(.+?)\"");
            var result = new List<string>();

            if (text.Contains("\"s\":"))
            {
                var start = text.IndexOf("\"s\":") + "\"s\":".Length;
                text = text.Substring(start);
                //text = text.TrimEnd('}');
                var matches = regex.Matches(text);
                foreach(System.Text.RegularExpressions.Match m in matches)
                {
                    result.Add(m.Groups[1].Value);
                }
            }

            return result;
        }

        private string Request(string url, int timeout = 60)
        {
            var request = WebRequest.Create(url);
            request.Method = "GET";
            //request.Timeout = timeout;
            request.ContentType = "text/html; charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        private string StringFormat(string text1, string text2)
        {
            var segment = Shuffle("111111222223333444556");
            string titleFormat;
            switch (segment)
            {
                case "2":
                    titleFormat = "{0}({1})";
                    break;
                case "3":
                    titleFormat = "{0} {1}";
                    break;
                case "4":
                    titleFormat = "{0}，{1}";
                    break;
                case "5":
                    titleFormat = "「{0}」{1}";
                    break;
                case "6":
                    titleFormat = "〈{0}〉{1}";
                    break;
                case "1":
                default:
                    titleFormat = "{0}_{1}";
                    break;
            }

            return string.Format(titleFormat, text1, text2);
        }

        private string Shuffle(string input)
        {
            Random random = new Random();
            char[] cArr = input.ToCharArray();
            string result = "";
            for (int i = input.Length - 1; i >= 0; i--)
            {
                int index = random.Next(0, i);
                result += cArr[index];
                cArr[index] = cArr[i];
            }

            return result.Substring(0, 1);
        }

        public T Rand<T>(List<T> source)
        {
            var random = new Random();
            var newList = new List<T>();
            foreach (var item in source)
            {
                newList.Insert(random.Next(newList.Count), item);
            }
            for (int i = 0; i < source.Count; i++)
            {
                source[i] = newList[i];
            }

            return source.First();
        }
    }
}
